package com.spider.common.web.controller;

import com.spider.common.utils.JsonUtil;
import com.spider.common.utils.R;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author marver
 * 2019/7/11 14:16
 * @description
 */
@Controller
public class WechatController {
    private static Logger logger = LoggerFactory.getLogger(WechatController.class);
    @Autowired
    private WxMpService wxMpService;

    @RequestMapping("/wx")
    public String index(){
        return "wxindex";
    }
    /**
     * 查询微信菜单
     * @throws Exception
     */
    @RequestMapping("wxMenu/queryWxMenu")
    @ResponseBody
    public R queryWxMenu(){
        try {
            wxMpService.getAccessToken(false);
            WxMpMenu wxMpMenu = wxMpService.getMenuService().menuGet();
            return R.ok().put("data", wxMpMenu);
        } catch (WxErrorException e) {
            logger.error(e.getMessage());
            return R.error("获取菜单失败");
        }
    }

    /**
     * 设置微信菜单
     * @param menu
     * @throws Exception
     */
    @RequestMapping("wxMenu/setUpWxMenu")
    @ResponseBody
    public R setUpWxMenu(@RequestBody WxMenu menu){
        try {
            //创建一级菜单
            logger.info(JsonUtil.getJsonByObj(menu));
            wxMpService.getMenuService().menuCreate(menu);
            return R.ok();
        } catch (WxErrorException e) {
            logger.error(e.getMessage());
            return R.error("创建菜单失败");
        }
    }
}
